package com.lmuse.xmr.foodspotting.db;

import android.util.Log;

import com.lmuse.xmr.foodspotting.model.Follower;
import com.lmuse.xmr.foodspotting.model.User;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class UserPresenterImpl implements Contract.UserPresenter {
    private static final String TAG = "UserPresenterImpl";

    private Contract.UserView userView;

    public UserPresenterImpl(Contract.UserView userView) {
        this.userView = userView;
    }

    @Override
    public void signUp(String username, String password) {
        final User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(username);
        user.setNickname(username);
        //注意：不能用save方法进行注册
        user.signUp(new SaveListener<User>() {
            @Override
            public void done(User s, BmobException e) {
                if(e==null){
                    userView.onSignUpSuccess(s);
                    //将注册后用户添加进follower表
                    initFollower(s.getObjectId());
                }else{
                    Log.i(TAG, "done: e ===================" + e.toString());
                    userView.onSignUpFailed(e.toString());
                }
            }
        });
    }

    /**
     * 将新增用户添加进follow表
     */
    void initFollower(String id) {
        final String userId = id;
        Follower follower = new Follower();
        follower.setUserId(id);
        follower.setFollowers(0);
        follower.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e != null) {
                    initFollower(userId);
                }
            }
        });
    }

    @Override
    public void signIn(String username, String password) {
        BmobUser user = new BmobUser();
        user.setUsername(username);
        user.setPassword(password);
        user.login(new SaveListener<BmobUser>() {

            @Override
            public void done(BmobUser bmobUser, BmobException e) {
                if(e==null){
                    User userCache = BmobUser.getCurrentUser(User.class);
                    userView.onSignInSuccess(userCache);
                }else{
                    Log.i(TAG, "done: e -----------" + e.toString());
                    userView.onSignInFailed(e.toString());
                }
            }
        });
    }

    @Override
    public void getUserInfoCache() {
        User userCache = BmobUser.getCurrentUser(User.class);
        userView.onUserInfoCache(userCache);
    }

    @Override
    public void updateUsername(String username) {
        BmobUser newUser = new BmobUser();
        newUser.setUsername(username);
        newUser.setEmail(username);
        BmobUser bmobUser = BmobUser.getCurrentUser(User.class);
        newUser.update(bmobUser.getObjectId(),new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if(e==null){
                    userView.onUpdateUserSuccess();
                }else{
                    userView.onUpdateUserFailed(e.toString());
                }
            }
        });
    }

    @Override
    public void updateNickname(String nickname) {
        User newUser = new User();
        newUser.setNickname(nickname);
        BmobUser bmobUser = BmobUser.getCurrentUser(User.class);
        newUser.update(bmobUser.getObjectId(),new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if(e==null){
                    userView.onUpdateUserSuccess();
                }else{
                    userView.onUpdateUserFailed(e.toString());
                }
            }
        });
    }

    @Override
    public void updatePassword(String oldPwd, String newPwd) {
        BmobUser.updateCurrentUserPassword(oldPwd, newPwd, new UpdateListener() {

            @Override
            public void done(BmobException e) {
                if(e==null){
                    userView.onUpdateUserSuccess();
                }else{
                    userView.onUpdateUserFailed(e.toString());
                }
            }

        });
    }

    @Override
    public void logOut() {
        BmobUser.logOut();   //清除缓存用户对象
    }

    @Override
    public void requestEmailVerify() {
        User userCache = BmobUser.getCurrentUser(User.class);
        String email = userCache.getEmail();
        BmobUser.requestEmailVerify(email, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                userView.onRequestEmailVerifyResult(e);
            }
        });
    }

    @Override
    public void resetPasswordByEmail(String email) {
        BmobUser.resetPasswordByEmail(email, new UpdateListener() {

            @Override
            public void done(BmobException e) {
                userView.onResetPasswordByEmailResult(e);
            }
        });
    }

    @Override
    public void queryUserById(String objectId) {
        BmobQuery<User> query = new BmobQuery<User>();
        query.getObject(objectId, new QueryListener<User>() {

            @Override
            public void done(User object, BmobException e) {
                if(e==null){
                    userView.onQueryUserByIdSuccess(object);
                }else{
                    userView.onQueryUserByIdFailed(e.toString());
                }
            }

        });
    }

    @Override
    public void queryUserAmount() {
        BmobQuery<User> bmobQuery = new BmobQuery<User>();
        bmobQuery.addQueryKeys("objectId");
        bmobQuery.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> list, BmobException e) {
                if (e == null) {
                    userView.onQueryUserAmountSuccess(list.size());
                }else {
                    userView.onQueryUserAmountFailed(e.toString());
                }
            }
        });
    }

    @Override
    public void queryByKey(String rowName) {
        BmobQuery<User> bmobQuery = new BmobQuery<User>();
        bmobQuery.addQueryKeys(rowName);
        bmobQuery.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if(e==null){
                    userView.onQueryByKeySuccess(object);
                    //注意：这里的Person对象中只有指定列的数据。
                }else{
                    userView.onQueryByKeyFailed(e.getMessage()+","+e.getErrorCode());
                }
            }
        });
    }

    @Override
    public void onDetach() {

    }
}
